package com.c.controller.admin;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.c.dto.PageDto;
import com.c.model.Log;
import com.c.result.LayResult;
import com.c.service.admin.LogService;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

@Controller
@RequestMapping("/log")
public class LogController {

	@Autowired
	public LogService ls;

	@RequestMapping("/list")
	@ResponseBody
	public LayResult<Log> showItem(HttpServletRequest request, HttpServletResponse response, PageDto pg) {
		return ls.getLogList(pg);
	}

	@RequestMapping("/download")
	public void downloadExcel(HttpServletRequest request, HttpServletResponse response) {
		PageDto pg = new PageDto();
		pg.setPage(1);
		pg.setLimit(1000);
		LayResult<Log> layResult = ls.getLogList(pg);
		// 通过工具类创建writer，默认创建xls格式
		ExcelWriter writer = ExcelUtil.getWriter();
		// 创建xlsx格式的
		// ExcelWriter writer = ExcelUtil.getWriter(true);
		// 一次性写出内容，使用默认样式
		writer.write(layResult.getData());
		// out为OutputStream，需要写出到的目标流
		try {
			// 设置response头信息
			response.reset();
			response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
			response.setHeader("Content-disposition", "attachment; filename=" + "log.xls");
			writer.flush(response.getOutputStream());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (IORuntimeException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭writer，释放内存
			writer.close();
		}
	}
}
